<template>
  <div class="main">
    <div
      class="main-table-header d-flex justify-content-between align-items-center"
    >
      <el-button
        style="padding: 8px 22px;border-radius:2px;"
        @click="handleCancel"
        >返回</el-button
      >
      <div v-if="tabIndex !== 'flow'">
        <el-button
          style="padding: 8px 22px;border-radius:4px;"
          @click="tabClick({ value: 'flow' })"
          >下一步</el-button
        >
      </div>
      <div v-else>
        <el-button
          style="padding: 8px 22px;border-radius:4px;"
          @click="tabClick({ value: 'base' })"
          >上一步</el-button
        >
        <el-button
          style="padding: 8px 22px;border-radius:4px;"
          type="primary"
          @click="sendClick"
          >发布</el-button
        >
      </div>
    </div>
    <div class="content">
      <div class="tab-wrap d-flex justify-content-between cursor-pointer">
        <div
          v-for="(item, index) in tabs"
          :key="index"
          :class="{
            tab_item_base: item.value === 'base',
            tab_item_flow: item.value === 'flow',
            tab_item_base__is: tabIndex === 'flow' && item.value === 'base',
            tab_item_flow__is: tabIndex === 'flow' && item.value === 'flow'
          }"
        >
          <i
            class="el-icon-success size-16"
            v-if="tabIndex === 'flow' && item.value === 'base'"
          ></i>
          {{ item.label }}
        </div>
      </div>
      <div style="width: 540px; margin: 0 auto;">
        <wk-form
          v-show="tabIndex === 'base'"
          ref="wkBaseFrom"
          customClass="''"
          :model="fieldsForm"
          :rules="fieldsRules"
          :field-from="fieldsForm"
          :field-list="fields"
          label-position="left"
          label-width="110px"
          @change="formChange"
        >
          <template slot-scope="{ data }">
            <!-- 人员选择器 -->
            <relate-empoyee
              v-if="data && data.formType == 'user-input'"
              :visible="userShow"
              :show-input="true"
              :isShowName="true"
              :user-id="fieldsForm.managerList"
              ref="relate_empoyee"
              @save="employeesSave"
              style="width: 100%;"
            />
            <template v-else>
              <slot :data="data" />
            </template>
          </template>
        </wk-form>
      </div>
      <div
        class="d-flex align-items-center justify-content-center"
        style="min-width: 540px;"
      >
        <wk-approve-flow
          v-show="tabIndex === 'flow'"
          ref="wkApproveFlow"
          :props="approveFlowConfig"
          :list="flowList"
          :send-node="sendNode"
        />
      </div>
    </div>
  </div>
</template>

<script>
import {
  examinesQueryFieldAPI,
  examinesAddAPI,
  examinesQueryExamineFlowAPI
} from "@/api/examine";
import RelateEmpoyee from "../components/RelateEmpoyee.vue"; // 人员选择器
import { WkApproveFlow, examineModel } from "@/components/ApprovalFlow";
import { objDeepCopy, getMaxIndex } from "@/utils";
import GenerateRulesMixin from "@/components/NewCom/WkForm/GenerateRules";
import ExamineInfoMinxin from "./mixins/ExamineInfo";
import WkForm from "@/components/NewCom/WkForm";

export default {
  name: "BusinessApproveFlowCreate",
  components: {
    WkApproveFlow,
    WkForm,
    RelateEmpoyee
  },
  filters: {},
  mixins: [GenerateRulesMixin, ExamineInfoMinxin],
  data() {
    return {
      loading: false,
      userShow: false, // 人员选择器弹框显示
      tabs: [
        {
          label: "第一步：基本信息",
          value: "base"
        },
        {
          label: "第二步：审批流程配置",
          value: "flow"
        }
      ],
      tabIndex: "base",
      sendNode: {
        name: "发起人",
        content: "具有新建权限的员工"
      },
      fields: [],
      fieldsForm: {},
      fieldsRules: {},
      flowList: [], // 数据源
      conditionFields: null
    };
  },
  computed: {
    approveFlowConfig() {
      return {
        conditionSelectRequest: examinesQueryFieldAPI,
        conditionSelectParams: {
          label: this.fieldsForm.label
        },
        conditionSelectList:
          this.fieldsForm.label === 3
            ? [
                {
                  fieldId: -1,
                  fieldName: "invoiceMoney",
                  fieldType: 1,
                  name: "开票金额",
                  setting: null,
                  type: 6
                },
                {
                  fieldId: -1,
                  fieldName: "invoiceType",
                  fieldType: 1,
                  name: "开票类型",
                  setting: [
                    {
                      label: "增值税专用发票",
                      value: "1"
                    },
                    {
                      label: "增值税普通发票",
                      value: "2"
                    },
                    {
                      label: "国税通用机打发票",
                      value: "3"
                    },
                    {
                      label: "地税通用机打发票",
                      value: "4"
                    },
                    {
                      label: "收据",
                      value: "5"
                    }
                  ],
                  type: 3
                }
              ]
            : null
      };
    },
    examine_detail() {
      if (this.$route.params.type == "edit") {
        const detail = JSON.parse(localStorage.getItem("examine_detail"));
        return detail;
      }
      return {};
    },
    // 审批流id
    examineId() {
      return this.$route.params.examineId != "0"
        ? this.$route.params.examineId
        : null;
    },
    // 操作类型
    examineType() {
      return this.$route.params.type ? this.$route.params.type : null;
    }
  },
  mounted() {
    // 如果有审批流id
    if (this.examineId) {
      this.getFlowList(this.examineId);
    } else {
      this.flowList = [objDeepCopy(examineModel)];
    }
    this.getBaseField();
  },
  methods: {
    /**
     * 获取流程详情
     */
    getFlowList(examineId) {
      examinesQueryExamineFlowAPI({ examineId })
        .then(res => {
          const list = res.data || [];
          const dataList = [];
          this.getListInfo(list, dataList);
          this.flowList = dataList;
        })
        .catch(() => {});
    },

    /**
     * 验证数据
     */
    validateSetting(item) {
      this.requestConditionFields().then(fields => {
        const field = fields.find(
          fieldItem => fieldItem.fieldName === item.fieldName
        );
        item.setting = field ? field.setting : [];
      });
    },

    requestConditionFields() {
      const {
        conditionSelectRequest,
        conditionSelectParams,
        conditionSelectList
      } = this.approveFlowConfig;
      if (conditionSelectList) {
        return Promise.resolve(conditionSelectList);
      }

      if (this.conditionFields) {
        return Promise.resolve(this.conditionFields);
      }
      return new Promise((resolve, reject) => {
        conditionSelectRequest(conditionSelectParams)
          .then(res => {
            const list = res.data || [];
            this.conditionFields = list;
            resolve(list);
          })
          .catch(() => {
            resolve([]);
          });
      });
    },

    /**
     * 获取自定义字段
     */
    getBaseField() {
      const field = [];
      const labelList = [
        { name: "合同", value: 1 },
        { name: "回款", value: 2 },
        // { name: "发票", value: 3 },
        // { name: "薪资", value: 4 },
        // { name: "采购审批", value: 5 },
        // { name: "采购退货审批", value: 6 },
        // { name: "销售审批", value: 7 },
        // { name: "销售退货审批", value: 8 },
        // { name: "付款审批", value: 9 },
        // { name: "回款审批", value: 10 },
        // { name: "盘点审批", value: 11 },
        // { name: "调拨审批", value: 12 },
        { name: "退款审批", value: 13 }
      ];

      field.push({
        field: "examineName",
        formType: "text",
        isNull: 1,
        name: "审批流名称",
        placeholder: "请输入",
        setting: [],
        inputTips: "",
        value: this.examine_detail ? this.examine_detail.examineName : ""
      });

      // 新建审批类型 默认为 oa_examine
      field.push({
        field: "label",
        formType: "select",
        isNull: 1,
        name: "审批业务",
        setting: labelList,
        value: this.examine_detail ? this.examine_detail.label : 1
      });

      field.push({
        field: "managerList",
        formType: "user-input",
        isNull: 1,
        name: "审批流管理员",
        setting: [],
        radio: true,
        inputTips: "",
        value: this.examine_detail.managerList
          ? this.examine_detail.managerList
          : []
      });

      field.push({
        field: "remarks",
        formType: "textarea",
        isNull: 0,
        name: "流程说明",
        maxlength: 200,
        setting: [],
        inputTips: "",
        value: this.examine_detail ? this.examine_detail.remarks : ""
      });

      this.handleFields(field);
    },

    /**
     * 调整字段
     */
    handleFields(list) {
      const fieldRules = {};
      const fieldForm = {};
      list.forEach(item => {
        if (item.formType === "userDep") {
          fieldForm.userList = [];
          fieldForm.deptList = [];
        } else {
          fieldRules[item.field] = this.getRules(item);
          fieldForm[item.field] = item.value;
        }
      });

      this.fields = objDeepCopy(list);
      this.fieldsForm = fieldForm;
      this.fieldsRules = fieldRules;
    },

    /**
     * change
     */
    formChange(item, index, value) {
      if (item.field === "label") {
        this.flowList = [objDeepCopy(examineModel)];
      }
    },

    /**
     * 发布点击
     */
    sendClick() {
      const flowParams = this.$refs.wkApproveFlow.getParams();
      flowParams.list.forEach(item => {
        const examineCCBo = {
          fieldList:
            item.examineCCBo.type == 3 ? item.examineCCBo.fieldList : [],
          type: item.examineCCBo.type,
          roleId: item.examineCCBo.type == 0 ? item.examineCCBo.roleId : [],
          deptId: item.examineCCBo.type == 1 ? item.examineCCBo.deptId : [],
          userId: item.examineCCBo.type == 2 ? item.examineCCBo.userId : []
        };
        item.examineCCBo = examineCCBo;
      });
      const params = {
        ...this.fieldsForm,
        dataList: flowParams.list
      };
      if (this.examineId) {
        params.examineId = this.examineId;
      }
      this.submiteRequest(params);
    },

    /**
     * 发送请求
     */
    submiteRequest(params) {
      examinesAddAPI(params)
        .then(res => {
          if (res && (res.code == 0 || res.code == 200)) {
            if (this.examineId) {
              this.$message.success("编辑成功");
            } else {
              this.$message.success("创建成功");
            }
            this.closeClick();
            this.handleCancel();
          }
        })
        .catch(() => {});
    },

    /**
     * 员工选择
     */
    employeesSave(e) {
      this.fieldsForm.managerList = e;
    },

    /**
     * 关闭
     */
    closeClick() {
      this.$emit("close");
    },

    // 流程点击
    tabClick(item) {
      // 下一步
      if (item.value == "flow") {
        // 校验表单数据
        this.$refs.wkBaseFrom.instance.validate(volid => {
          if (volid) {
            this.tabIndex = item.value;
          }
        });
      } else {
        this.tabIndex = item.value;
      }
    },
    /**
     * 返回
     */
    handleCancel() {
      this.$router.go(-1);
    }
  }
};
</script>
<style lang="scss" scoped>
.main {
  width: 100%;
  min-height: 100%;
  background-color: #fff;
  .main-table-header {
    height: 50px;
    background-color: white;
    position: relative;
    padding: 0 16px;
    border-bottom: 1px solid #e5e5e5;
  }

  .content {
    min-width: 540px;
    margin: 0 auto;
    .tab-wrap {
      width: 540px;
      margin: 40px auto;
      .tab_item_base {
        width: 265px;
        height: 40px;
        color: #fff;
        text-align: center;
        line-height: 40px;
        background-color: #0066f9;
        position: relative;
      }
      .tab_item_base::after {
        content: " ";
        display: block;
        position: absolute;
        right: -30px;
        top: 0;
        width: 0;
        height: 0;
        border-top: 20px solid transparent;
        border-right: 10px solid transparent;
        border-left: 20px solid #0066f9;
        border-bottom: 20px solid transparent;
        z-index: 1;
      }
      .tab_item_base__is {
        background-color: #4fd8a3;
      }
      .tab_item_base__is::after {
        border-left: 20px solid #4fd8a3;
      }
      .tab_item_flow {
        width: 265px;
        height: 40px;
        color: #fff;
        text-align: center;
        line-height: 40px;
        background-color: #e5e5e5;
        position: relative;
      }
      .tab_item_flow__is {
        background-color: #0066f9;
      }
      .tab_item_flow::before {
        content: " ";
        display: block;
        position: absolute;
        left: 0px;
        top: 0;
        width: 0;
        height: 0;
        border-top: 20px solid transparent;
        border-right: 10px solid transparent;
        border-left: 20px solid #fff;
        border-bottom: 20px solid transparent;
      }
    }
  }
}

::v-deep .el-form-item {
  margin-bottom: 16px;
}
</style>
